package com.jksoft.darewayyyy;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jksoft.darewayyyy.adapter.EmployeeAdapter;
import com.jksoft.darewayyyy.fragment.ScanFragment;
import com.jksoft.darewayyyy.global.MyApplication;
import com.jksoft.darewayyyy.pojo.Employee;
import com.jksoft.darewayyyy.util.FileUtils;
import com.jksoft.darewayyyy.util.JPushUtil;
import com.jksoft.darewayyyy.util.LogUtil;
import com.jksoft.darewayyyy.util.OkHttpClientManager;
import com.jksoft.darewayyyy.util.PushServiceThread;
import com.jksoft.darewayyyy.util.QRCodeUtil;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.squareup.okhttp.Request;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import cn.pedant.SweetAlert.SweetAlertDialog;


public class MainActivity extends AppCompatActivity implements PushServiceThread.PushServiceInterface {
    private final static String TAG = MainActivity.class.getSimpleName();
    //for receive customer msg from jpush server
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.jksoft.darewayyyy.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";
    public static boolean isForeground = false;
    private List<Employee> employeeList;
    EmployeeAdapter adapter;
    @ViewInject(R.id.toolbar)
    Toolbar toolbar;
    @ViewInject(R.id.queueList)
    RecyclerView queueList;
    @ViewInject(R.id.qrcode)
    ImageView qrcode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerMessageReceiver();
        setContentView(R.layout.activity_main);
        ViewUtils.inject(this);

        setSupportActionBar(toolbar);

//        JPushInterface.init(getApplicationContext());
//        JPushInterface.setDebugMode(false);

        initBlueTooth();
        initQrCode();
        initScan();
        // 启动监听线程
        PushServiceThread pt = new PushServiceThread();
        pt.setPushListener(this);
        pt.start();
    }

    private void initScan() {
        getSupportFragmentManager().beginTransaction().replace(R.id.scanArea, ScanFragment.newInstance()).commit();
    }


    @Override
    protected void onResume() {
        super.onResume();
        isForeground = true;
        JPushInterface.onResume(this);
    }


    //**************************************************************************
    //*            BlueTooth
    //**************************************************************************

    public void initBlueTooth() {
        employeeList = new ArrayList<>();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);

        adapter = new EmployeeAdapter(this, employeeList);
        queueList.setHasFixedSize(true);
        queueList.setLayoutManager(linearLayoutManager);
        queueList.setAdapter(adapter);
    }

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        registerReceiver(mMessageReceiver, filter);
    }

    @Override
    public void onSuccess(Employee employee) {
        addToAdapter(employee);
    }


    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            try {
                Log.i(TAG, "onReceive");
                if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
//                    String extras = intent.getStringExtra(KEY_EXTRAS);
//                    StringBuilder showMsg = new StringBuilder();
//                    if (!JPushUtil.isEmpty(extras)) {
//                        showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
//                        Log.e(TAG, extras);
//                        Gson gson = new GsonBuilder().create();
//                        Employee employee = gson.fromJson(extras, Employee.class);
//                        addEmployee(employee);
//                    } else {
//
//                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //*******************************************************
    //*          TwoDimensionCode
    //********************************************************
    public void initQrCode() {
        OkHttpClientManager okHttpClientManager = OkHttpClientManager.getInstance();
        OkHttpClientManager.Param params[] = new OkHttpClientManager.Param[1];
        params[0] = new OkHttpClientManager.Param("type", "tablet");
        okHttpClientManager.getPostDelegate().postAsyn(MyApplication.qrcodeUrl, params, new OkHttpClientManager.ResultCallback<String>() {
            @Override
            public void onError(Request request, Exception e) {
                LogUtil.e(TAG, "excption" + e.getMessage());
            }

            @Override
            public void onResponse(String response) {
                Log.e(TAG, response);
                generateQrcode(response);
            }
        });
    }

    public void generateQrcode(String data) {
        try {
            JSONObject qrJson = new JSONObject();
            Toast.makeText(MainActivity.this, data, Toast.LENGTH_SHORT).show();
            JSONObject jsonObject = new JSONObject(data);
            qrJson.put("url", MyApplication.checkByQrcodeUrl);
            qrJson.put("k", jsonObject.getString("key"));
            QRCodeUtil qrCodeUtil = new QRCodeUtil(this);
            qrCodeUtil.createQRImage(qrJson.toString(), qrcode);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                initQrCode();
            }
        }, 3600000);
    }
//
//    public void addEmployee(final Employee employee) {
//
//        OkHttpClientManager okHttpClientManager = OkHttpClientManager.getInstance();
//        OkHttpClientManager.Param[] params = new OkHttpClientManager.Param[1];
//        params[0] = new OkHttpClientManager.Param("empId", employee.getEmpId());
//        okHttpClientManager.getPostDelegate().postAsyn(MyApplication.getUserInfoUrl, params, new OkHttpClientManager.ResultCallback<String>() {
//            @Override
//            public void onError(Request request, Exception e) {
//
//            }
//
//            @Override
//            public void onResponse(String response) {
//                addToAdapter(employee, response);
//            }
//        });
//    }

    public void addToAdapter(Employee employee) {
//        try {
//            String photo = result.getString("photo");
//            byte[] imgByte = Base64.decode(photo, Base64.DEFAULT);
//            Bitmap bitmap = BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);
//            FileUtils fileUtils = new FileUtils(this);
//            String savePath = fileUtils.saveBitmap(bitmap, employee.getEmpId() + ".png");
//            employee.setImgUrl(savePath);

        adapter.addItem(employee);
        queueList.scrollToPosition(0);
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mMessageReceiver);
    }
}
